// 多语言方法
var lang = function(tag) {
    return window.languageResource[tag] || '';
};
$(function () {
    $('body').inputAction({
        global: true
    }).height($(window).height());

    // 常用正则
    window.commonRegexp = {
        'mobile': {
            'regexp': /^.{1,}$/,
            'message': lang('tip.mobile'),
            'emptyMessage': lang('tip.mobileWrite'),
        },
        'password': {
            // 'regexp': /^(?=^[a-zA-Z0-9]{6,20}$).*[a-zA-Z]+.*$/,
            'regexp': /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{6,20}$/,
            'message': lang('tip.password'),
            'emptyMessage': lang('tip.passwordNull'),
        },
        'imageCode': {
            'regexp': /^[0-9a-zA-Z]{4}$/,
            'message': lang('common.verification'),
            'emptyMessage': lang('common.verificationNull'),
        },
        'address': /^.{1,255}$/,
        'vcode': {
            'regexp': /^\d{4}$/,
            'message': lang('tip.message'),
            'emptyMessage': lang('tip.messageWrite'),
        },
        'smsvcode': /^\w{6}$/
    };
    if ($.fn.lazyload !== undefined) {
        $('.lazyload').lazyload({
            effect: 'fadeIn'
        });
    }

    // 初始化区号选择
    var areaCode;
    if ($.cookie("area_book_cookie") != 'undefined') {
        areaCode = $.cookie("area_book_cookie");
        if (areaCode != undefined) {
            $('.areaCode').find('.areaCodeValue').text(areaCode);
        } else {
            $('.areaCode').find('.areaCodeValue').text('86');
        }
    }  
    $('.areaCode').on('click', '.dropdown-menu a', function() {
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_book_cookie") != 'undefined') {
            $.cookie('area_book_cookie', value, { expires: 7, path: '/' });
        }
    });    
    //设置语言cookie
    $(".languageSwitch").find("a").click(function(){
       $.cookie('mz_think_language', $(this).attr('data-language'), { expires: 7, path: '/' });
       //重载当前页面
       var timestamp = Date.parse(new Date());
       window.location.href = (window.location.href).split('&rev')[0]+'&rev='+timestamp;
    });    
});
// 显示或隐藏加载中动画
/* exported toggleLoading */
var toggleLoading = function (isShow) {
    if (isShow) {
        $('#loadingContainer').removeClass('hidden');
        $('body').addClass('modal-open');
    } else {
        $('#loadingContainer').addClass('hidden');
        $('body').removeClass('modal-open');
    }
};
// 获取Get参数
/* exported getArgs */
var getArgs = function getArgs() {
    var args = {};
    var query = location.search.substring(1);
    // Get query string
    var pairs = query.split("&");
    // Break at ampersand
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        // Look for "name=value"
        if (pos == -1) {
            continue;
        }
        // If not found, skip
        var argname = pairs[i].substring(0, pos); // Extract the name
        var value = pairs[i].substring(pos + 1); // Extract the value
        value = decodeURIComponent(value); // Decode it, if needed
        args[argname] = value;
        // Store as a property
    }
    return args; // Return the object
};
//ajax异步请求
/* exported ajaxRequest */
var ajaxRequest = function (url, params, method, successcallback, errorcallback, obj) {
    if (method === null || method === '') {
        method = 'get';
    }
    if (obj !== undefined) {
        if (obj.attr('disabled') !== undefined) {
            return false;
        }
        obj.attr('disabled', true);
    }
    $.ajax({
        url: url,
        data: params,
        type: method,
        cache: false,
        dataType: 'json',
        success: function (data) {
            if (obj !== undefined) {
                obj.removeAttr('disabled');
            }
            if (typeof successcallback == 'function') {
                successcallback(data, obj);
            } else {
                window.location.reload();
            }
        },
        error: function (error) {
            if (obj !== undefined) {
                obj.removeAttr('disabled');
            }
            if (typeof errorcallback == 'function') {
                errorcallback(error, obj, defaultErrorHandler);
            } else {
                defaultErrorHandler(error, obj);
            }
        }
    });
};
//一般的ajax请求error处理
/* exported defaultErrorHandler */
var defaultErrorHandler = function (error, obj) {
    if (typeof error.responseJSON === 'undefined') {
        formInlineTip(obj, lang('ServerInternalError'));
    } else if (error.responseJSON.status === 303) {
        var getParams = getArgs();
        window.location.href = '/Home/BookPage/index?hotel=' + getParams.hotel;
    } else {
        formInlineTip(obj, error.responseJSON.info);
    }
};
//延时跳转到url
/* exported timeoutForward */
var timeoutForward = function (url, time) {
    if (url === undefined || url === '') {
        url = window.location.href;
    }
    if (time === undefined) {
        time = 1500;
    }
    window.setTimeout(function () {
        window.location.href = url;
    }, time);
};
//按钮等待
/* exported timeDisplay */
var timeDisplay = function (objbtn, time) {
    objbtn.addClass('disabled');
    objbtn.attr('disabled', true);
    var i = time;
    var id = window.setInterval(function () {
        i = i - 1;
        objbtn.find('.displayTime').text('(' + i + ')');
        if (i === 0) {
            window.clearInterval(id);
            objbtn.find('.displayTime').text('');
            objbtn.html('<span class="displayTime"></span>'+lang('timeDisplay')+'</div>');
            objbtn.removeClass('disabled');
            objbtn.removeAttr('disabled');
        }
    }, 1000);
};
// 刷新验证码
/* exported refreshVcode */
var refreshVcode = function () {
    var imgCodeObj = $('#imgcode');
    var vcodeUrl = imgCodeObj.attr('src');
    var indexOfQuestionMark = vcodeUrl.indexOf('?');
    if (indexOfQuestionMark !== -1) {
        vcodeUrl = vcodeUrl.substr(0, indexOfQuestionMark);
    }
    var time = new Date().getTime();
    imgCodeObj.attr('src', vcodeUrl + '?' + time);
};
/* exported formInlineTip */
var formInlineTip = function (obj, info, type) {
    formInlineRight(obj);
    if (type === undefined) {
        type = 0;
    }
    // 检测data中是否定义了显示提示的另一个位置
    var tipObjectStr = $(obj).data('tip-object');
    var tipObject = $(tipObjectStr);
    var hasTipObject = tipObject.length !== 0;
    if (!hasTipObject) {
        tipObject = obj;
    }
    var formGroupObj = tipObject.parents('.form-group');
    var helpBlock = formGroupObj.find('.help-block');
    helpBlock.html(info);
    var tipClass = '';
    switch (type) {
        case 2:
            tipClass = 'has-warning';
            break;
        case 1:
            tipClass = 'has-success';
            break;
        case 0:
            tipClass = 'has-error';
            break;
        default:
            break;
    }
    // 根据tip的类型改变help颜色
    formGroupObj.addClass(tipClass);
    if (hasTipObject) {
        obj.parent().addClass(tipClass);
    }
};
/**
 * 去除表单help-block状态
 * @param  Object obj  jquery对象
 */
/* exported formInlineRight */
var formInlineRight = function (obj) {
    var formGroupObj = $(obj).parents('.form-group');
    formGroupObj.removeClass('has-error');
    formGroupObj.removeClass('has-warning');
    formGroupObj.removeClass('has-success');
    // 检测data中是否定义了显示提示的另一个位置
    var tipObjectStr = $(obj).data('tip-object');
    var tipObject = $(tipObjectStr);
    var hasTipObject = tipObject.length !== 0;
    if (hasTipObject) {
        formGroupObj = tipObject.parents('.form-group');
        formGroupObj.removeClass('has-error');
        formGroupObj.removeClass('has-warning');
        formGroupObj.removeClass('has-success');
    }
};

/**
 * 根据传入字符串获取日期对象
 * @param  string input 暂只支持yyyy-MM-dd，2007-04-19格式
 * @return Date
 */
/* exported getDate */
var getDate = function (input) {
    if (input === '') {
        return new Date();
    }
    var splitsDate = input.split('-');
    return new Date(splitsDate[1] + '/' + splitsDate[2] + '/' + splitsDate[0]);
};
/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * @param  string mask 默认为yyyy-MM-dd
 * @example
 * var customDate = new Date().customFormat("yyyy-MM-dd");
 * @return string
 */
Date.prototype.customFormat = function(mask) {
    if (mask === undefined) {
        mask = 'yyyy-MM-dd';
    }
    var d = this;
    var zeroize = function(value, length) {
        if (!length) {
            length = 2;
        }
        value = String(value);
        for (var i = 0, zeros = ''; i < length - value.length; i++) {
            zeros += '0';
        }
        return zeros + value;
    };
    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function($0) {
        switch ($0) {
            case 'd':
                return d.getDate();
            case 'dd':
                return zeroize(d.getDate());
            case 'ddd':
                return [
                    'Sun',
                    'Mon',
                    'Tue',
                    'Wed',
                    'Thr',
                    'Fri',
                    'Sat'
                ][d.getDay()];
            case 'dddd':
                return [
                    'Sunday',
                    'Monday',
                    'Tuesday',
                    'Wednesday',
                    'Thursday',
                    'Friday',
                    'Saturday'
                ][d.getDay()];
            case 'M':
                return d.getMonth() + 1;
            case 'MM':
                return zeroize(d.getMonth() + 1);
            case 'MMM':
                return [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ][d.getMonth()];
            case 'MMMM':
                return [
                    'January',
                    'February',
                    'March',
                    'April',
                    'May',
                    'June',
                    'July',
                    'August',
                    'September',
                    'October',
                    'November',
                    'December'
                ][d.getMonth()];
            case 'yy':
                return String(d.getFullYear()).substr(2);
            case 'yyyy':
                return d.getFullYear();
            case 'h':
                return d.getHours() % 12 || 12;
            case 'hh':
                return zeroize(d.getHours() % 12 || 12);
            case 'H':
                return d.getHours();
            case 'HH':
                return zeroize(d.getHours());
            case 'm':
                return d.getMinutes();
            case 'mm':
                return zeroize(d.getMinutes());
            case 's':
                return d.getSeconds();
            case 'ss':
                return zeroize(d.getSeconds());
            case 'l':
                return zeroize(d.getMilliseconds(), 3);
            case 'L':
                var m = d.getMilliseconds();
                if (m > 99) {
                    m = Math.round(m / 10);
                }
                return zeroize(m);
            case 'tt':
                return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT':
                return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z':
                return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
            default:
                return $0.substr(1, $0.length - 2);
        }
    });
};
/**
 * 根据需要加减天数，
 * @param  integer interval 负数时是前几天,正数时是后几天
 * @example
 * var diffDays = new Date().customDays(7); 获取7天的后Date对象
 * @return Date
 */
Date.prototype.customDays = function(interval) {
    var thisTime = this.getTime();
    return new Date(thisTime + interval * 86400000);
};